﻿function showContest() {
	var pageSize = 20;
	if (refreshTab('showContest'))
		return;
	var showPreview = window.screen.width > 800;
	function renTitle(value, p, record) {
		if (showPreview)
			return String
					.format(
							'{0}.&nbsp; '
									+ '<a href="javascript:void(0);" onclick="contestProblemList({0});" class="likelink" style="color:black;font-weight:bold">{1}</a>'
									+ '<br />', record.data.cid, value);
		return String
				.format(
						'{0}.&nbsp; '
								+ '<a href="javascript:void(0);" onclick="contestProblemList({0});" class="likelink" style="color:black;font-weight:bold">{1}</a>',
						record.data.eid, value);
	}

	function renRun(value, p, record) {
		if (value == 2)
			return "<span style='color:grey'>Ended</span>";
		else if (value == 1)
			return "<span style='color:red'>Running</span>";
		else if (value == 0)
			return "<span style='color:green'>Pending</span>";
	}
	function renPub(value, p, record) {
		if (value)
			return "<span style='color:blue'>public</span>";
		else
			return "<span style='color:black'>private</span>";
	}
	var store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : url.showContest
						}),
				reader : new Ext.data.JsonReader({
							root : 'result',
							totalProperty : 'total',
							id : 'cid'
						}, ['cid', 'title', 'startTime', 'overTime',
								'is_public', 'opening', 'description'])
			});// ContestList store
	store.on("load", onDesEdit);
	store.load({
				params : {
					start : 0,
					limit : pageSize,
					god : sys.god
				}
			});
	var expander = new Ext.ux.RowExpander({
				tpl : new Ext.Template('<p>{description}</p><br>')
			});
	var cm = new Ext.grid.ColumnModel([{
				header : 'Contest Title',
				sortable : false,
				dataIndex : 'title',
				width : 500,
				renderer : renTitle
			}, {
				header : 'isPublic',
				sortable : false,
				dataIndex : 'is_public',
				width : 100,
				renderer : renPub
			}, {
				header : 'Contest Running',
				sortable : false,
				dataIndex : 'opening',
				width : 200,
				renderer : renRun
			}]);

	var sm = new Ext.grid.RowSelectionModel({
				singleSelect : true
			});
	function getSelect() {// 选择触发器，返回选择的record
		if (sm.getCount() == 0)
			return null;
		return sm.getSelected();
	}
	var pagebar = new Ext.PagingToolbar({
				pageSize : pageSize,
				store : store,
				displayInfo : true,
				emptyMsg : '当前没有比赛。',
				displayMsg : '当前显示第 {0} - {1} 题，共 {2}。',
				items : [new Ext.Toolbar.Spacer({
							width : 5
						})],
				plugins : new Ext.ux.SlidingPager()
			});

	var toolbar = new Ext.Toolbar({
				items : [new Ext.Button({
									text : '刷新',
									iconCls : 'refresh-icon',
									handler : function() {
										store.reload();
									}
								}), new Ext.Button({
									text : '描述',
									iconCls : 'preview-icon',
									enableToggle : true,
									pressed : showPreview,
									toggleHandler : function(sender, pressed) {
										showPreview = pressed;
										grid.view.refresh();
									}
								}), new Ext.Toolbar.Separator(),
						new Ext.Button({
									text : '进入',
									disabled : true,
									handler : onShowPList
								})]
			});

	var godbuttons;
	if (sys.god) {// 上帝模式
		godbuttons = [new Ext.Toolbar.Separator(), new Ext.Button({
							text : '添加比赛',
							iconCls : 'add-icon',
							handler : addOrEditContest
						}), new Ext.Button({
							text : '编辑比赛',
							iconCls : 'edit-icon',
							handler : onEdit,
							disabled : true
						}), new Ext.Button({
							text : '删除比赛',
							iconCls : 'delete-icon',
							handler : onDelete,
							disabled : true
						})];
		toolbar.add(godbuttons);
	}
	var grid = new Ext.grid.GridPanel({// 面板主控件
		id : 'showContest',
		title : 'Contest',
		closable : true,
		region : 'center',
		loadMask : {
			msg : '载入中...'
		},
		viewConfig : {
			forceFit : true,
			enableRowBody : true,
			showPreview : showPreview,
			getRowClass : previewFormat,
			scrollToRow : function(rowIndex) {
				var firstRow = Ext.get(this.getRow(0));
				var row = Ext.get(this.getRow(rowIndex));
				var distance = row.getOffsetsTo(firstRow)[1];
				this.scroller.dom.scrollTop = distance;
			}
		},
		store : store,
		cm : cm,
		sm : sm,
		tbar : toolbar,
		bbar : pagebar,
		plugins : expander,
		collapsible : true,
		animCollapse : false
	});
	ui.contestList = grid;
	sm.on('selectionchange', onSelect);
	grid.on('rowdblclick', onShowPList);
	function onSelect() {
		var record = getSelect();
		var disable = !record;
		toolbar.get(3).setDisabled(disable);
		if (record) {
			for (var i = 0; i < store.getCount(); ++i) {
				expander.collapseRow(i);
			}
			var rowIndex = store.indexOf(record);
			if (rowIndex == -1)
				alert("false");
			expander.expandRow(rowIndex);
		}
		if (sys.god) {
			godbuttons[2].setDisabled(disable);
			godbuttons[3].setDisabled(disable);
		}
	}
	addTab(grid);
	function onDelete() {
		var record = getSelect();
		if (!record)
			return;
		deleteContest(record.data.cid);
		store.reload();
	}
	function previewFormat(record, rowIndex, p) {
		if (showPreview) {
			p.body = String.format('<p>{0}</p>', Ext.util.Format
							.trim(Ext.util.Format
									.stripTags(record.data.description.replace(
											/&nbsp;/g, ' ')))
							.gbtrim(window.screen.width > 800 ? 120 : 60));
			return 'x-grid3-row-expanded';
		}
		return
		'x-grid3-row-collapsed';
	}
	function onDesEdit() {
		for (var i = 0; i < store.getCount(); ++i) {
			store.getAt(i).data.description = store.getAt(i).data.description
					.replace(/\r\n/g, '<br/>');
			store.getAt(i).data.description = store.getAt(i).data.description
					.replace(/\n/g, '<br/>');
		}
	}
	function onEdit() {
		var record = getSelect();
		addOrEditContest(record.data)
	}

	function onShowPList() {
		var record = getSelect();
		if(!sys.user)
		{
			showLogin();
			return;
		}
		if (!record)
			return;
		contestProblemList(record.data.cid);
	}
}

function refreshContest(page) {
	var grid = ui.contestList;
	var store = grid.store;
	store.reload();
}
